/**
 * Copyright (c) 2010 Abadi Kurniawan, Brian Dukes
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package hackathon.android.mymessageinbox;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

/**
 * @author Abadi Kurniawan, Brian Dukes
 *
 */
public class MyMessage extends ListActivity {
	private static String token;
	private static String userName;
	private MyService mBoundService;
	private MyAdapter listAdapter;
	private boolean mIsBound;
	private String webServiceUrl;

	private ServiceConnection mConnection = new ServiceConnection() {
	    public void onServiceConnected(ComponentName className, IBinder service) {
	        mBoundService = ((MyService.MessageBinder)service).getService();
	    }

	    public void onServiceDisconnected(ComponentName className) {
	        mBoundService = null;
	    }
	};

	void doBindService() {
		Intent serviceIntent = new Intent(this, MessageService.class);
		serviceIntent.putExtra(MyService.EXTRA_TOKEN, token);
		serviceIntent.putExtra(MyService.EXTRA_USERNAME, userName);
		serviceIntent.putExtra(MyService.EXTRA_WEB_SERVICE_URL, webServiceUrl);
		bindService(serviceIntent, mConnection, BIND_AUTO_CREATE);
		startService(serviceIntent);
	    mIsBound = true;
	}

	void doUnbindService() {
	    if (mIsBound) {
	    	unregisterReceiver(listAdapter);
	        stopService(new Intent(this, MessageService.class));
	        unbindService(mConnection);
	        mIsBound = false;
	    }
	}
	
	@Override
	protected void onResume () {
		super.onResume();
        // Clear notification for our service.
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(R.string.service_id);        
	}

	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    doUnbindService();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        webServiceUrl = prefs.getString(getString(R.string.settings_url_name), "");
        
        Bundle extra = getIntent().getExtras();
        if(extra == null || extra.getString(MyService.EXTRA_TOKEN) == null) {
        	Intent loginIntent = new Intent();
        	loginIntent.setClass(this, LoginActivity.class);
        	startActivity(loginIntent);
        	this.finish();
        }else {
        	MyMessage.token = extra.getString(MyService.EXTRA_TOKEN);
        	MyMessage.userName = extra.getString(MyService.EXTRA_USERNAME);
        	setContentView(R.layout.main);
        	if (!mIsBound)
        	{
        		doBindService();
        	}
        	listAdapter = new MyAdapter(this, userName);
            setListAdapter(listAdapter);            
            registerReceiver(listAdapter, new IntentFilter(MessageService.INTENT_MESSAGE_UPDATE));            
        }
    }
    
    @Override

    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Log.d("Engage", "[MyMessage] onListItemClick()");
    	Message msg = (Message)listAdapter.getItem(position);
    	Intent viewerIntent = new Intent();
    	viewerIntent.setClass(this, ViewerActivity.class);
    	viewerIntent.putExtra(ViewerActivity.EXTRA_MESSAGE, msg);
    	viewerIntent.putExtra(ViewerActivity.EXTRA_MESSAGE_POSITION, position);
    	viewerIntent.putExtra(ViewerActivity.EXTRA_MESSAGE_LIST, listAdapter.messages);
    	startActivity(viewerIntent);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_compose:
            compose();
            return true;
        case R.id.menu_settings:
        	settings();
        	return true;
        case R.id.menu_logout:
            logout();
            return true;
        case R.id.menu_quit:
        	quit();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private void compose()
    {
    	
    }
    
    private void logout()
    {
    	token = null;
    	userName = null;
    	
    	Intent loginIntent = new Intent();
    	loginIntent.setClass(this, LoginActivity.class);
    	startActivity(loginIntent);
    	listAdapter.close();       
    	this.finish();
    }
    
    private void settings()
    {
    	Intent settingsActivity = new Intent(getBaseContext(),
    			Preferences.class);
    	startActivity(settingsActivity);
    }
    
    private void quit()
    {
    	new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
            	listAdapter.close();
                MyMessage.this.finish();    
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();
    }
    
    class MessageReceiver extends BroadcastReceiver
    {

		@Override
		public void onReceive(Context context, Intent intent) {
			
		}   	
    }
}